package cn.tj.student.web.servlet;

import cn.tj.student.dao.UserDao;
import cn.tj.student.dao.impl.UserDaoImpl;
import cn.tj.student.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        //获取账号密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //创建Dao
        UserDao userDao=new UserDaoImpl();
        //调用登录查询方法
        User user = userDao.queryByNameAndPassword(new User(null, username, password));
        //根据查询结果判断登录状态
        if(user!=null){//成功跳管理首页index
            //将帐号储存到作用域
//            req.setAttribute("",username);
            //通过请求对象
            HttpSession session = req.getSession();
            session.setAttribute("username_in_session",username);
            //获取上下文对象
//            ServletContext servletContext = req.getServletContext();
//            servletContext.setAttribute("",username);
            resp.sendRedirect("/index.jsp");
        }else{//失败跳转到登录
            resp.sendRedirect("/login.jsp");
        }
    }
}
